package com.papers.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.exception.ServiceException;
import com.papers.common.helper.LoginHelper;
import com.papers.common.utils.DateUtils;
import com.papers.common.utils.StringUtils;
import com.papers.system.domain.TJuanDepartment;
import com.papers.system.domain.TJuanMajor;
import com.papers.system.domain.bo.TJuanDepartmentBo;
import com.papers.system.domain.vo.TJuanDepartmentVo;
import com.papers.system.mapper.TJuanDepartmentMapper;
import com.papers.system.mapper.TJuanMajorMapper;
import com.papers.system.service.ITJuanDepartmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 院系Service业务层处理
 *
 * @author papers
 * @date 2022-10-08
 */
@RequiredArgsConstructor
@Service
public class TJuanDepartmentServiceImpl implements ITJuanDepartmentService {

    private final TJuanDepartmentMapper baseMapper;
    private final TJuanMajorMapper tJuanMajorMapper;

    /**
     * 查询院系
     */
    @Override
    public TJuanDepartmentVo queryById(String departId) {
        return baseMapper.selectVoById(departId);
    }

    /**
     * 查询院系列表
     */
    @Override
    public TableDataInfo<TJuanDepartmentVo> queryPageList(TJuanDepartmentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TJuanDepartment> lqw = buildQueryWrapper(bo);
        lqw.orderByAsc(TJuanDepartment::getDepartCode);
        Page<TJuanDepartmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询院系列表
     */
    @Override
    public List<TJuanDepartmentVo> queryList(TJuanDepartmentBo bo) {
        LambdaQueryWrapper<TJuanDepartment> lqw = buildQueryWrapper(bo);
        lqw.select(TJuanDepartment::getDepartCode, TJuanDepartment::getDepartName,
                        TJuanDepartment::getCreatedBy, TJuanDepartment::getCreatedTime)
                .orderByAsc(TJuanDepartment::getDepartCode);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TJuanDepartment> buildQueryWrapper(TJuanDepartmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TJuanDepartment> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDepartCode()), TJuanDepartment::getDepartCode, bo.getDepartCode());
        lqw.like(StringUtils.isNotBlank(bo.getDepartName()), TJuanDepartment::getDepartName, bo.getDepartName());
        lqw.eq(StringUtils.isNotBlank(bo.getDepartDesp()), TJuanDepartment::getDepartDesp, bo.getDepartDesp());
        lqw.eq(StringUtils.isNotBlank(bo.getCreatedBy()), TJuanDepartment::getCreatedBy, bo.getCreatedBy());
        lqw.eq(bo.getCreatedTime() != null, TJuanDepartment::getCreatedTime, bo.getCreatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdatedBy()), TJuanDepartment::getUpdatedBy, bo.getUpdatedBy());
        lqw.eq(bo.getUpdatedTime() != null, TJuanDepartment::getUpdatedTime, bo.getUpdatedTime());
        return lqw;
    }

    /**
     * 新增院系
     */
    @Override
    public Boolean insertByBo(TJuanDepartmentBo bo) {
        //获取院系对象//
        TJuanDepartment add = BeanUtil.toBean(bo, TJuanDepartment.class);

        add.setUpdatedBy(LoginHelper.getUsername());
        add.setCreatedBy(LoginHelper.getUsername());
        add.setCreatedTime(DateUtils.getNowDate());
        add.setUpdatedTime(DateUtils.getNowDate());

        LambdaQueryWrapper<TJuanDepartment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(TJuanDepartment::getDepartCode).last("LIMIT 1");
        TJuanDepartment department = baseMapper.selectOne(queryWrapper);
        String newCode;
        if (ObjectUtils.isNull(department)) {
            newCode = "01";
        } else {
            List<String> departments = baseMapper.selectCodeList();
            int oldCode = Integer.parseInt(department.getDepartCode().substring(1));
            if (oldCode != departments.size()) {
                int currentCode = 01;
                for (String code : departments) {
                    if (currentCode != Integer.parseInt(code)) {
                        oldCode = currentCode - 1;
                        break;
                    }
                    currentCode++;
                }
            }
            oldCode++;
            if (oldCode > 99) {
                throw new ServiceException("已达到院系最大数量，请联系管理员");
            }
            newCode = String.format("%02d", oldCode);
        }
        add.setDepartCode("Y" + newCode);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setDepartId(add.getDepartId());
        }
        return flag;
    }

    /**
     * 修改院系
     */
    @Override
    public Boolean updateByBo(TJuanDepartmentBo bo) {
        TJuanDepartment update = BeanUtil.toBean(bo, TJuanDepartment.class);
        /*设置更新时间、更新用户*/
        update.setUpdatedBy(LoginHelper.getUsername());
        update.setUpdatedTime(DateUtils.getNowDate());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除院系
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (String id : ids) {
            QueryWrapper<TJuanMajor> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(TJuanMajor::getDepartId, id);
            List<TJuanMajor> list = tJuanMajorMapper.selectList(queryWrapper);
            if (list.size() > 0) {
                throw new ServiceException("该院系下有专业存在，删除失败");
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 院系code唯一约束判断
     */
    @Override
    public int DepartCodeUnique(TJuanDepartmentBo bo) {
        LambdaQueryWrapper<TJuanDepartment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TJuanDepartment::getDepartCode, bo.getDepartCode());
        queryWrapper.last("LIMIT 1");
        TJuanDepartmentVo tJuanDepartmentVo = baseMapper.selectVoOne(queryWrapper);
        /*如存在相同code的对象，返回0*/
        if (tJuanDepartmentVo == null) {
            return 1;
        }
        if (tJuanDepartmentVo.getDepartId().equals(bo.getDepartId())) {
            return 1;
        }
        return 0;
    }

    /**
     * 查询专业院系名称
     *
     * @return
     */
    @Override
    public List<TJuanDepartmentVo> getMajorDepName() {
        return baseMapper.getDepartmentNameList();
    }

    /**
     * 查询院系
     *
     * @param depName
     * @return
     */
    @Override
    public TJuanDepartment getOne(String depName) {
        LambdaQueryWrapper<TJuanDepartment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(depName != null, TJuanDepartment::getDepartName, depName);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public R getDepartmentList() {
        return R.ok(baseMapper.selectList());
    }

    /**
     * 导入 院系
     *
     * @param list
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R save(List<TJuanDepartment> list) {
        List<TJuanDepartment> list1 = new ArrayList<>();
        List<TJuanDepartment> list2 = new ArrayList<>();
        for (TJuanDepartment item : list) {
            if (null != item.getDepartCode()) {
                list1.add(item);
            } else {
                list2.add(item);
            }
        }
        list1.addAll(list2);
        String newCode;
        for (TJuanDepartment item : list1) {
            if (null == item.getDepartName()) {
                return R.fail("存在院系名称为空，请修改");
            }
            if (null != item.getDepartCode() && item.getDepartCode().substring(1).length() == 1) {
                item.setDepartCode("Y0" + item.getDepartCode().substring(1));
            }
            if (null != item.getDepartCode() &&
                    (item.getDepartCode().substring(1).length() != 2
                    || Integer.parseInt(item.getDepartCode().substring(1)) <= 0
                    || Integer.parseInt(item.getDepartCode().substring(1)) > 99)) {
                return R.fail("存在院系编号格式有误，请修改");
            }
            //没有code
            if (ObjectUtils.isNull(item.getDepartCode())) {
                LambdaQueryWrapper<TJuanDepartment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.orderByDesc(TJuanDepartment::getDepartCode)
                        .last("LIMIT 1");
                TJuanDepartment department = baseMapper.selectOne(queryWrapper);
                if (ObjectUtils.isNull(department)) {
                    newCode = "01";
                } else {
                    List<String> departments = baseMapper.selectCodeList();
                    int oldCode = Integer.parseInt(department.getDepartCode().substring(1));
                    ;
                    if (oldCode != departments.size()) {
                        int currentCode = 01;
                        for (String code : departments) {
                            if (currentCode != Integer.parseInt(code.substring(1))) {
                                oldCode = currentCode - 1;
                                break;
                            }
                            currentCode++;
                        }
                    }
                    oldCode++;
                    if (oldCode > 99) {
                        return R.fail("已达到院系最大数量，请联系管理员");
                    }
                    newCode = String.format("%02d", oldCode);
                }
                item.setDepartCode("Y" + newCode);
                item.setCreatedBy(LoginHelper.getUsername());
                item.setCreatedTime(DateUtils.getNowDate());
            }
            //有code
            else {
                //重复，更新信息
                if (codeVerify(item)) {
                    LambdaQueryWrapper<TJuanDepartment> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TJuanDepartment::getDepartCode, item.getDepartCode());
                    TJuanDepartment department = baseMapper.selectOne(queryWrapper);
                    if (StringUtils.isNotBlank(department.getDepartId())) {
                        item.setDepartId(department.getDepartId());
                    }
                }
                //没有重复，新增
                else {
                    item.setCreatedBy(LoginHelper.getUsername());
                    item.setCreatedTime(DateUtils.getNowDate());
                }
            }
            item.setUpdatedBy(LoginHelper.getUsername());
            item.setUpdatedTime(DateUtils.getNowDate());
            baseMapper.insertOrUpdate(item);
        }
        return R.ok("导入成功");

    }

    /**
     * 验证编码是否唯一
     *
     * @param item
     * @return
     */
    public boolean codeVerify(TJuanDepartment item) {
        List<TJuanDepartment> tJuanDepartments = baseMapper.selectList();
        for (TJuanDepartment tJuanDepartment : tJuanDepartments) {
            if (item.getDepartCode() != null && item.getDepartCode().equals(tJuanDepartment.getDepartCode())) {
                return true;
            }
        }
        return false;
    }
}
